package com.ruoyi.common.utils;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import javax.servlet.http.HttpServletRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.mobile.weixin.service.WeixinOrder;
import com.ruoyi.common.utils.qiniu.QiNiuUploadUtil;
import com.ruoyi.common.utils.uniquekey.WorkerIdGenerator;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.member.domain.Member;
import com.vdurmont.emoji.EmojiParser;

import static com.ruoyi.project.AppBeanInjector.weixinConfig;
import static com.ruoyi.project.AppBeanInjector.wxMpService;

//import com.lwxf.commons.exception.ErrorCodes;
//import com.lwxf.commons.utils.LwxfStringUtils;
//import com.lwxf.newstore.webapp.baseservice.cache.constant.RedisConstant;
//import com.lwxf.newstore.webapp.baseservice.rabbitmq.MessageEntity;
//import com.lwxf.newstore.webapp.baseservice.rabbitmq.MessageScope;
//import com.lwxf.newstore.webapp.common.enums.MQEventEnum;
//import com.lwxf.newstore.webapp.common.enums.user.UserSex;
//import com.lwxf.newstore.webapp.common.mobile.weixin.XMLUtils;
//import com.lwxf.newstore.webapp.common.mobile.weixin.template.ImgJsonMsg;
//import com.lwxf.newstore.webapp.common.mobile.weixin.template.TextJsonMsg;
//import com.lwxf.newstore.webapp.common.utils.ExceptionGenerateFactory;
//import com.lwxf.newstore.webapp.domain.entity.user.UserThirdInfo;
//import com.lwxf.newstore.webapp.facade.AppBeanInjector;
//
//import static com.lwxf.newstore.webapp.facade.AppBeanInjector.*;

/**
 * 功能：
 *
 * @author：renzhongshan(d3shan@126.com)
 * @create：2018-05-24 15:21
 * @version：2018 1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
public abstract class WeixinUtils {
	private static final Logger logger = LoggerFactory.getLogger(WeixinUtils.class);
	private static final String TRADE_TYPE = "xcx";
	public static final String CHARSET = "utf-8";
	private static String Key = "JLx6W8PNHUOCGdIcuHiqYZ20S5Z4xN2d";


	/**
	 * appid:公众号的唯一标识
	 *
	 *redirect_uri:重定向的url,就是授权后要跳转的页面
	 *
	 *scope:应用授权作用域
	 *
	 *		snsapi_base:不弹出授权页面，直接跳转，只能获取用户openid
	 *
	 *		snsapi_userinfo:弹出授权页面，可通过openid拿到昵称、性别、所在地
	 *
	 *state:重定向后带的参数
	 */
	private static String c_web_authorization_path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state={2}#wechat_redirect";
	public static final String c_auth_scope_login = "snsapi_login";


	public static HttpURLConnection createConnection(String url, String method) throws Exception {
		return createConnection(url, method, "application/x-www-form-urlencoded",null);
	}

	public static HttpURLConnection createConnection(String url, String method, String contentType,String outputStr) throws Exception {
		URL requstUrl = new URL(url);
		HttpURLConnection http = (HttpURLConnection) requstUrl.openConnection();
		http.setRequestMethod(method);
		http.setRequestProperty("Content-Type", contentType);// 当outputStr不为null时向输出流写数据
		http.setDoOutput(true);
		http.setDoInput(true);
		if (null != outputStr) {
			OutputStream outputStream = http.getOutputStream();
			// 注意编码格式
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}
		System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
		System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
		return http;
	}

	private static String _parseFromHttpURLConncection(HttpURLConnection httpConnection) throws Exception {
		Assert.notNull(httpConnection,"httpConnection不能为空");
		InputStream is = httpConnection.getInputStream();
		int size = is.available();
		byte[] jsonBytes = new byte[size];
		is.read(jsonBytes);
		String message = new String(jsonBytes, "UTF-8");
		is.close();
		return message;
	}

	public static JSONObject parseFromHttpURLConncection(HttpURLConnection httpConnection) throws Exception {
		String message = _parseFromHttpURLConncection(httpConnection);
		return new JSONObject(message);
	}

	public static JSONObject parseFromHttpURLConncectionForEmoji(HttpURLConnection httpConnection) throws Exception {
		String message = EmojiParser.removeAllEmojis(_parseFromHttpURLConncection(httpConnection));
		return new JSONObject(message);
	}

	/**
	 * java后台获取用户微信信息
	 *
	 * @param openId
	 * @return
	 */
//	public static UserThirdInfo getUserWeixinInfoByOpenId(String openId) {
//		WxMpUser wxMpUser = null;
//		try {
//			logger.info("查询微信用户信息UserThirdInfo:getUserWeixinInfoByOpenId():openId:{}",openId);
//			wxMpUser = wxMpService.getUserService().userInfo(openId);
//			logger.info("根据微信信息构造UserThirdInfo:getUserWeixinInfoByOpenId():nickName:{}",wxMpUser.getNickname());
//			UserThirdInfo weixinInfo = new UserThirdInfo();
//			weixinInfo.setWxOpenId(wxMpUser.getOpenId());
//			weixinInfo.setWxUnionId(wxMpUser.getUnionId());
//			weixinInfo.setWxNickname(wxMpUser.getNickname());
//			return weixinInfo;
//		} catch (WxErrorException e) {
//			logger.error(e.getMessage());
//		}
//		return null;
//	}

	/**
	 * 根据WxMpUser创建UserThirdInfo
	 *
	 * @param wxMpUser
	 * @return
	 */
//	public static UserThirdInfo createUserThirdInfoByWxMpUser(WxMpUser wxMpUser) {
//		UserThirdInfo thirdInfo = new UserThirdInfo();
//		thirdInfo.setWxOpenId(wxMpUser.getOpenId());
//		thirdInfo.setWxUnionId(wxMpUser.getUnionId());
//		thirdInfo.setWxNickname(wxMpUser.getNickname());
//		thirdInfo.setWxIsBind(Boolean.TRUE);
//		thirdInfo.setWxIsSubscribe(Boolean.TRUE);
//		thirdInfo.setEmailIsBind(Boolean.FALSE);
//		thirdInfo.setMobileIsBind(Boolean.FALSE);
//		return thirdInfo;
//	}

	/**
	 * 根据微信openId获取微信用户的信息
	 *
	 * @param openId
	 * @return
	 */
	public static WxMpUser getWxMpUserByOpenId(String openId) {
		WxMpUser wxMpUser;
		try {
			wxMpUser = wxMpService.getUserService().userInfo(openId);
		} catch (WxErrorException e) {
			wxMpUser = null;
			logger.error(e.getMessage());
		}
		return wxMpUser;
	}


//	/**
//	 * 通过网页授权方式获取微信用户信息
//	 *
//	 * @param openId
//	 * @param accessToken
//	 * @return
//	 */
//	public static UserWeixinInfo getUserWeixinInfoForWeb(String openId, String accessToken) {
//		String url = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
////		url = LwxfStringUtils.format(url, accessToken, openId);
//		url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
//		return getUserWeixinInfo(url);
//	}
//
//	private static UserWeixinInfo getUserWeixinInfo(String url) {
//		HttpURLConnection connection = null;
//		try {
//			connection = createConnection(url, RequestMethod.GET.toString());
//			connection.connect();
//			JSONObject jsonObj = parseFromHttpURLConncectionForEmoji(connection);
//			System.out.println(jsonObj.toString());
//			if (jsonObj.has("errcode")) {
//				throw new BaseException("获取异常");
////				throw ExceptionGenerateFactory.createException(ErrorCodes.BIZ_LOAD_USER_WEIXIN_INFO_10021);
//			}
//			UserWeixinInfo weixinInfo = new UserWeixinInfo();
//			weixinInfo.setOperId(jsonObj.getString("openid"));
//			weixinInfo.setUnionId(jsonObj.getString("unionid"));
//			//如果nickName存在 就赋值 不存在 就使用默认值
//			weixinInfo.setNickName(jsonObj.optString("nickname","who is me?"));
//			return weixinInfo;
//		} catch (Exception e) {
//			logger.error("获取用户的微信信息出现异常", e);
//		} finally {
//			if (connection != null) {
//				connection.disconnect();
//			}
//		}
//		return null;
//	}


	public static JSONObject getWebAuthorizeInfo(String code){
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
		url = FBSStringUtil.format(url, weixinConfig.getAppId(), weixinConfig.getAppsecret(), code);
//		url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf668b30b40cb70b5&secret=a3b2b5dd79f51c610a40cdbd4a3601aa&code="+code+"&grant_type=authorization_code";
		try {
			HttpURLConnection connection = createConnection(url, RequestMethod.GET.toString());
			connection.connect();
			JSONObject jsonObj = parseFromHttpURLConncection(connection);
			connection.disconnect();
			return jsonObj;
		} catch (Exception e) {
			logger.error("获取用户的微信信息出现异常", e);
		}
		return null;
	}

	/**
	 *  微信端获取用户信息
	 * @param code
	 * @return
	 */
	public static JSONObject getWeiXinAuthorizeInfo(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
		//url = LwxfStringUtils.format(url, weixinCfg.getAppId(), weixinCfg.getSecret(), code);
		url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+weixinConfig.getAppId()+"&secret="+weixinConfig.getAppsecret()+"&code="+code+"&grant_type=authorization_code";
		try {
			HttpURLConnection connection = createConnection(url, RequestMethod.GET.toString());
			connection.connect();
			JSONObject jsonObj = parseFromHttpURLConncection(connection);
			connection.disconnect();
			return jsonObj;
		} catch (Exception e) {
			logger.error("获取用户的微信信息出现异常", e);
		}
		return null;
	}

	public static String getWebAuthorizationPath(HttpServletRequest request, String weixinAppId) throws UnsupportedEncodingException {
		return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weixinConfig.getAppId()+"&redirect_uri=http://threedata.ngrok.xiaomiqiu.cn/api/user/code&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
	}

	public static JSONObject getXCXToken() {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
		url = FBSStringUtil.format(url,weixinConfig.getAppId(),weixinConfig.getAppsecret());
		try {
			HttpURLConnection connection = createConnection(url, RequestMethod.GET.toString());
			connection.connect();
			JSONObject jsonObject = parseFromHttpURLConncection(connection);
			connection.disconnect();
			return jsonObject;
		} catch (Exception e) {
			logger.error("获取用户信息出现异常",e);
		}
		return null;
	}

	public static String getPerpayId(SortedMap<String,Object> data,SortedMap<String,Object> data2) {
		String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		try {
			HttpURLConnection connection = createConnection(url,RequestMethod.POST.toString(),"application/x-www-form-urlencoded",getXml(data));

			// 从输入流读取返回内容
			InputStream inputStream = connection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			connection.disconnect();
			System.out.println(buffer.toString());
			Map<String,String> resultMap = null;
			resultMap = doXMLParse(buffer.toString());
			if(resultMap!=null){
				String nonce_str = resultMap.get("nonce_str");
				String prepay_id = resultMap.get("prepay_id");
				data2.put("nonceStr",nonce_str);
				return prepay_id;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String getXml(SortedMap<String,Object> data) {
		String xml ="<xml>\n" +
				"   <appid>"+data.get("appid")+"</appid>\n" +
				"   <attach>"+data.get("attach")+"</attach>" +
				"   <openid>"+data.get("openid")+"</openid>" +
				"   <body>"+data.get("body")+"</body>" +
				"   <mch_id>"+data.get("mch_id")+"</mch_id>" +
				"   <nonce_str>"+data.get("nonce_str")+"</nonce_str>" +
				"   <notify_url>"+data.get("notify_url")+"</notify_url>" +
				"   <out_trade_no>"+data.get("out_trade_no")+"</out_trade_no>" +
				"   <spbill_create_ip>"+data.get("spbill_create_ip")+"</spbill_create_ip>" +
//				"   <time_start>"+DateUtils.getDate()+"</time_start>" +
				"   <total_fee>"+data.get("total_fee")+"</total_fee>" +
				"   <trade_type>"+data.get("trade_type")+"</trade_type>" +
				"   <sign>"+createSign(CHARSET,data)+"</sign>" +
				"</xml>";
		return xml;
	}


	public static void getRefuse(SortedMap<String,Object> data) {
		String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
		try {
			HttpURLConnection connection = createConnection(url,RequestMethod.POST.toString(),"application/x-www-form-urlencoded",getRefundXml(data));

			// 从输入流读取返回内容
			InputStream inputStream = connection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			connection.disconnect();
			System.out.println(buffer.toString());
			Map<String,String> resultMap = null;
			resultMap = doXMLParse(buffer.toString());
			if(resultMap!=null){
				System.out.println(resultMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private static String getRefundXml(SortedMap<String,Object> data) {
		String xml ="<xml>\n" +
				"   <appid>"+data.get("appid")+"</appid>\n" +
				"   <mch_id>"+data.get("mch_id")+"</mch_id>" +
				"   <nonce_str>"+data.get("nonce_str")+"</nonce_str>" +
				"   <notify_url>"+data.get("notify_url")+"</notify_url>" +
				"   <out_trade_no>"+data.get("out_trade_no")+"</out_trade_no>" +
//				"   <time_start>"+DateUtils.getDate()+"</time_start>" +
				"   <refund_fee>"+data.get("refund_fee")+"</refund_fee>" +
				"   <total_fee>"+data.get("total_fee")+"</total_fee>" +
				"   <sign>"+createSign(CHARSET,data)+"</sign>" +
				"</xml>";
		return xml;
	}

//	public static String getWebAuthorizationPath(String callPath, String weixinAppId, String sessionId) throws UnsupportedEncodingException {
//		return LwxfStringUtils.format(c_web_authorization_path, weixinAppId, URLEncoder.encode(callPath, StandardCharsets.UTF_8.name()), 1);
//	}

	/**
	 * 发送文本消息
	 * @param msg
	 * @param toUser
	 */
//	public static void sendTextMsgToUser(String msg, String toUser) {
//		TextJsonMsg msgObj = new TextJsonMsg();
//		msgObj.setTouser(toUser);
//		msgObj.setContentInfo(msg);
//		AppBeanInjector.weixinJsonMsgService.pushMsg(msgObj);
//	}

	/**
	 * 发送图片消息
	 * @param
	 * @param toUser
	 */
//	public static void sendImgMsgToUser(String toUser,String mediaId){
//		ImgJsonMsg msgObj = new ImgJsonMsg();
//		msgObj.setTouser(toUser);
//		msgObj.setMediaId(mediaId);
//		AppBeanInjector.weixinJsonMsgService.pushMsg(msgObj);
//	}

	/**
	 * 发送mq消息
	 * @param event
	 * @param userId
	 */
//	public static void sendErrorMsgToUser(MQEventEnum event,String code, String msg,String userId) {
//		MessageEntity error = MessageEntity.newOne(MessageScope.USER,userId ,event);
//		Map map = new HashMap(1);
//		Map m = new HashMap(2);
//		m.put("code", code);
//		m.put("msg", msg);
//		map.put("error", m);
//		error.setData(map);
//		error.setX_TAG(AppBeanInjector.idGererateFactory.nextStringId());
//		error.setScope(MessageScope.USER);
//		error.setScopeId(userId);
//		//AppBeanInjector.rabbitMQSender.sendMessage(true,error); TODO:
//	}

	/**
	 * 请求转发到远程，请接收响应
//	 * @param remoteUrl
//	 * @param queryString
//	 * @param reqXmlData
	 * @return
	 */
//	public static ResponseData doForwardRequest(String remoteUrl, String queryString, Map<String,String> reqXmlData){
//		HttpURLConnection httpURLConnection = null;
//		OutputStream out = null;
//		ResponseData responseData = new ResponseData();
//		try{
//			String path = remoteUrl+ "?" + queryString;
//			logger.debug("微信请求转发远程url:{}", path);
//			URL url = new URL(path);
//			httpURLConnection = (HttpURLConnection) url.openConnection();
//			httpURLConnection.setReadTimeout(10000);
//			httpURLConnection.setRequestMethod("POST");
//			httpURLConnection.setDoOutput(true);
//			httpURLConnection.setDoInput(true);
//
//			httpURLConnection.setRequestProperty("Content-Type", "application/xml");
//			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
//			httpURLConnection.setRequestProperty("Charset", "UTF-8");
//
//			//发送数据
//			out = httpURLConnection.getOutputStream();
//			String xml = XMLUtils.parseMapToXml(reqXmlData);
//			out.write(xml.getBytes(StandardCharsets.UTF_8));
//			out.flush();
//
//			//响应
//			int resultCode = httpURLConnection.getResponseCode();
//			logger.debug("微信请求转发响应码:{}",  resultCode);
//
//			BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
//			ByteArrayOutputStream bos = new ByteArrayOutputStream();
//			int len;
//			byte[] arr = new byte[1024];
//			while((len=bis.read(arr))!= -1){
//				bos.write(arr,0,len);
//				bos.flush();
//			}
//			bos.close();
//			bis.close();
//
//			responseData.setCode(resultCode);
//			responseData.setData(bos.toString("utf-8"));
//		}catch (Exception e){
//			logger.error(e.getMessage());
//		}finally {
//			if(httpURLConnection != null){
//				httpURLConnection.disconnect();
//			}
//			if(out != null){
//				try {
//					out.close();
//				} catch (IOException e) {
//					logger.error(e.getMessage());
//				}
//			}
//		}
//		return responseData;
//	}

	public static class ResponseData {
		private int code;
		private String data;

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		public String getData() {
			return data;
		}

		public void setData(String data) {
			this.data = data;
		}
	}

	/**
	 * 初始化用户微信状态
	 * @param wxOpenId
	 */
//	public static Integer initPlatformTag(String wxOpenId){
//		Integer platformTag = (Integer) AppBeanInjector.redisUtils.hGet(RedisConstant.PLATFORM_TAG, wxOpenId);
//
//		if(platformTag != null){
//			return platformTag;
//		}
//
//		boolean newLwxfBind = false;
//		List<UserThirdInfo> userThirdInfoList = userThirdInfoFacade.findByWxOpenId(wxOpenId);
//		if(userThirdInfoList.isEmpty()){
//			newLwxfBind = true;
//		}
//		if(newLwxfBind){
//			platformTag = 0;
//		}else {
//			platformTag = 1;
//		}
//		if(platformTag != null){
//			AppBeanInjector.redisUtils.hPut(RedisConstant.PLATFORM_TAG, wxOpenId, platformTag);
//		}
//		return platformTag;
//	}
//	public static int transitionWeiXinUserSex(int weiXinSex){
//		if(weiXinSex==0||weiXinSex==1){
//			return UserSex.MAN.getValue();
//		}else{
//			return UserSex.WOMEN.getValue();
//		}
//	}


	public static String getQrCodeImg(Member member) {
		String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={0}";
		url = FBSStringUtil.format(url,getXCXToken().get("access_token"));
		RestTemplate rest = new RestTemplate();

		HashMap<String, Object> map = new HashMap<>();
		map.put("path","pages/home/index/index?introUser="+member.getId());
		map.put("width",430);
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		HttpEntity requestEntity = new HttpEntity<>(map, headers);
		ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
		// System.out.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
		byte[] result = entity.getBody();
		String file = "/qrCode/"+member.getId() + ".jpg";
		String fileName = RuoYiConfig.getUploadPath()+ file;
		FileUploadUtils.getFileByBytes(result,fileName);
		file = AppBeanInjector.serverConfig.getUrl()+Constants.RESOURCE_PREFIX+"/upload"+file;
		String http= file.substring(0,5);
		if(!http.equals("https")){
			file=file.replaceFirst("http","https");
		}
		return file;
	}



	/**
	 * 微信支付签名算法sign
	 * @param characterEncoding
	 * @param parameters
	 * @return
	 */
	public static String createSign(String characterEncoding,SortedMap<String,Object> parameters){
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			Object v = entry.getValue();
			if(null != v && !"".equals(v)
					&& !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + Key);
		System.out.println("xxxxxxx:"+sb);
		String sign = Md5Utils.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
		return sign;
	}


	//xml解析
	public static Map doXMLParse(String strxml) throws JDOMException, IOException {

		if(null == strxml || "".equals(strxml)) {
			return null;
		}

		Map m = new HashMap();

		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if(children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}

			m.put(k, v);
		}

		//关闭流
		in.close();

		return m;
	}

	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if(!children.isEmpty()) {
			Iterator it = children.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if(!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

}
